package com.iqiyi.pps.epg.core.service.news;

import com.iqiyi.pps.epg.api.model.web.news.TNewsDetailsData;
import com.iqiyi.pps.epg.api.model.web.news.TNewsDetailsDataPage;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.dao.news.NewsDetailsDataDao;
import com.iqiyi.pps.epg.core.model.news.NewsDetails;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang on 2016/11/28.
 */
@Service
@Transactional
public class NewsDetailsDataServiceImpl implements NewsDetailsDataService {

    public static Logger logger = LoggerFactory.getLogger(NewsDetailsDataServiceImpl.class);

    @Autowired
    private NewsDetailsDataDao dao;

    @Override
    public void saveNewsDetails(NewsDetails entity) {
        if (entity == null)
            return;
        dao.save(entity);
    }

    @Override
    public TNewsDetailsDataPage findTNewsDetailsDataPage(TPage page, TFilter filter) {
        Map<String, String> map = filter.getFilters();
        String tempPattern = "${PARAMS}";
        String totalPattern = "select COUNT(*)";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String hql = tempPattern + " from NewsDetails";
        Page<NewsDetails> dbPage = TransUtil.buildPage(page);

        hql = TransUtil.buildQueryStringByPropertyFilter(dbPage, hql, filterList);

        if (dbPage.isAutoCount()) {
            String totalCount = dao.getSession().createQuery(hql.replace(tempPattern, totalPattern)).uniqueResult().toString();
            page.setTotalCount(Long.valueOf(totalCount));
        }

        List result = dao.getSession().createQuery(hql.replace(tempPattern, ""))
                .setMaxResults(dbPage.getPageSize())
                .setFirstResult((dbPage.getPageNo() - 1) * dbPage.getPageSize())
                .list();
        TNewsDetailsDataPage tNewsDetailsDataPage = new TNewsDetailsDataPage();
        tNewsDetailsDataPage.setTPage(page);
        List<TNewsDetailsData> tNewsDetailsDatas = new ArrayList<TNewsDetailsData>();
        for(Object obj : result) {
            NewsDetails newsDetails = (NewsDetails) obj;
            tNewsDetailsDatas.add(newsDetails.convertThriftModel());
        }
        tNewsDetailsDataPage.setResult(tNewsDetailsDatas);
        return tNewsDetailsDataPage;
    }
}
